package br.com.marcelo.reservasis.client.pagina.hospede;

import br.com.aroeirasoftware.gwtcomponents.client.components.ASButton;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASFieldSize;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASForm;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASMessagePanel;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASMessagePanel.ASMessageSeverity;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASOperation;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASPage;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASTogglePanel;
import br.com.aroeirasoftware.gwtcomponents.client.i18n.ASGWTComponentsI18N;
import br.com.marcelo.reservasis.client.componentes.ReservaSISApplication;
import br.com.marcelo.reservasis.client.i18n.ReservaSISI18N;
import br.com.marcelo.reservasis.client.services.hospede.HospedeUIService;
import br.com.marcelo.reservasis.domain.model.Hospede;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Marcelo
 */
public class HospedeCriarAlterarPagina extends ASPage {

    private Hospede hospede;
    private ASOperation operacao;
    private ASForm form;
    private ASButton bConfirmar;
    private ASButton bCancelar;
    private ClickHandler clickHandler;
    private ASTogglePanel painelPrincipal;

    public HospedeCriarAlterarPagina(ASPage paginaAnterior) {
        super(paginaAnterior, ReservaSISApplication.getInstance(), ReservaSISI18N.messages.tituloHospedeCriarPagina(), ReservaSISI18N.messages.subtituloHospedeCriarPagina("Asterisco"));
        this.operacao = ASOperation.CRIACAO;
        this.hospede = GWT.create(Hospede.class);
    }

    public HospedeCriarAlterarPagina(ASPage paginaAnterior, Hospede hospede) {
        super(paginaAnterior, ReservaSISApplication.getInstance(), ReservaSISI18N.messages.tituloHospedeAlterarPagina(), ReservaSISI18N.messages.subtituloHospedeAlterarPagina("Asterisco"));
        this.operacao = ASOperation.ALTERACAO;
        this.hospede = hospede;
    }

    @Override
    public void configurarComponentes() {
        clickHandler = new ClickHandler() {

            public void onClick(ClickEvent event) {
                Object source = event.getSource();

                if (source == bConfirmar) {
                    boolean formulariosValidos = isFormulariosValidos();

                    if (!formulariosValidos) {
                        ASMessagePanel.getInstance().exibirMensagem(
                                ASGWTComponentsI18N.messages.msgProblemasFormulario(),
                                ASMessagePanel.ASMessageSeverity.ERRO,
                                ASMessagePanel.ASMessageOption.OK);
                        return;
                    }
                    preparar();
                    if (operacao == ASOperation.CRIACAO) {
                        salvar(hospede);
                    } else if (operacao == ASOperation.ALTERACAO) {
                        alterar(hospede);
                    }
                }
                if (source == bCancelar) {
                    fechar();
                }
            }
        };

        form = new ASForm();
        form.addCampoTexto("nome", ReservaSISI18N.messages.nome(), true, ASFieldSize.ENORME);
        form.addCampoTexto("identidade", ReservaSISI18N.messages.identidade(), false, ASFieldSize.PEQUENO);
        form.addCampoTextoFormatado("cpf", ReservaSISI18N.messages.cpf(), "999.999.999-99", "999.999.999-99", "999.999.999-99", false, ASFieldSize.MEDIO);
        form.addCampoTextoFormatado("telefone", ReservaSISI18N.messages.telefone(), "(99)9999-9999", "(99)9999-9999", "(99)9999-9999", false, ASFieldSize.MEDIO);
        form.focalizarPrimeiroCampo();

        painelPrincipal = new ASTogglePanel(ReservaSISI18N.messages.hospede());
        painelPrincipal.setWidth("100%");

        painelPrincipal.add(form);

        add(painelPrincipal);

        bConfirmar = new ASButton(ASGWTComponentsI18N.messages.btnConfirmar(), clickHandler);
        bConfirmar.addEstiloDefault();
        bCancelar = new ASButton(ASGWTComponentsI18N.messages.btnCancelar(), clickHandler);

        addComando(bConfirmar);
        addComando(bCancelar);
    }

    @Override
    public void configurarDados() {
        if (operacao.equals(ASOperation.ALTERACAO)) {
            HospedeUIService.Async.getInstance().getPorId(hospede.getIdhospede(), new AsyncCallback<Hospede>() {

                @Override
                public void onFailure(Throwable caught) {
                    ASMessagePanel.getInstance().exibirMensagem("Erro ao recuperar",
                            ASMessageSeverity.ERRO, ASMessagePanel.ASMessageOption.OK);
                }

                @Override
                public void onSuccess(Hospede result) {

                    hospede = result;

                    Map<String, Object> valores = new HashMap<String, Object>();
                    valores.put("nome", hospede.getNome());
                    valores.put("identidade", hospede.getIdentidade());
                    valores.put("cpf", hospede.getCpf());
                    valores.put("telefone", hospede.getTelefone());

                    form.setValue(valores);
                }
            });
        }
    }

    public void salvar(final Hospede hospede) {
        HospedeUIService.Async.getInstance().salvar(hospede, new AsyncCallback<Integer>() {

            public void onFailure(Throwable caught) {
                ASMessagePanel.getInstance().exibirMensagem(
                        ReservaSISI18N.messages.msgErro(
                        ReservaSISI18N.messages.gCriar(), caught),
                        ASMessageSeverity.ERRO, ASMessagePanel.ASMessageOption.OK);
            }

            public void onSuccess(Integer result) {
                hospede.setIdhospede(result);


                ASMessagePanel.getInstance().exibirMensagem(
                        ReservaSISI18N.messages.msgSucesso(
                        ReservaSISI18N.messages.hospede(),
                        hospede.getNome(),
                        ReservaSISI18N.messages.gCriado()),
                        ASMessageSeverity.SUCESSO, ASMessagePanel.ASMessageOption.OK, new Command() {

                    public void execute() {
                        fechar();
                    }
                });
            }
        });
    }

    public void alterar(final Hospede hospede) {
        HospedeUIService.Async.getInstance().atualizar(hospede, new AsyncCallback<Void>() {

            public void onFailure(Throwable caught) {
                ASMessagePanel.getInstance().exibirMensagem(
                        ReservaSISI18N.messages.msgErro(
                        ReservaSISI18N.messages.gAtualizar(), caught),
                        ASMessageSeverity.ERRO, ASMessagePanel.ASMessageOption.OK);
            }

            public void onSuccess(Void result) {

                ASMessagePanel.getInstance().exibirMensagem(
                        ReservaSISI18N.messages.msgSucesso(
                        ReservaSISI18N.messages.hospede(),
                        hospede.getNome(),
                        ReservaSISI18N.messages.gAtualizado()),
                        ASMessageSeverity.SUCESSO, ASMessagePanel.ASMessageOption.OK, new Command() {

                    public void execute() {
                        fechar();
                    }
                });
            }
        });
    }

    public void preparar() {

        hospede.setNome((String) form.getValue().get("nome"));
        hospede.setIdentidade((String) form.getValue().get("identidade"));
        hospede.setCpf((String) form.getValue().get("cpf"));
        hospede.setTelefone((String) form.getValue().get("telefone"));

    }

    public boolean isFormulariosValidos() {
        boolean result = true;
        if (!form.isValido()) {
            result = false;
        }
        return result;
    }

    public void remove(ASForm fom) {
        painelPrincipal.remove(fom);
    }
}


